import { Service } from "maishu-chitu-service";
// import { config } from "../config";
import { errors } from "../errors";

let service = new Service();
let miniProgram = {
    appId: "wxb6238f6a8f843b2e",
    secret: "4f3877061a4daf7600900e227a4745b1"
}
export let auth = {
    code2Session: async (code: string) => {
        if (!code) throw errors.argumentNull("code");

        let url = `https://api.weixin.qq.com/sns/jscode2session`;
        let args = {
            appid: miniProgram.appId,
            secret: miniProgram.secret,
            js_code: code,
            grant_type: "authorization_code"
        }

        type Result = { session_key: string, openid: string };
        return get<Result>(url, args);
    }
}

async function get<T>(url: string, args: any): Promise<T> {
    let r = await service.get<T>(url, args);
    if (typeof r == "string") {
        r = JSON.parse(r);
    }

    let err = r as any as ResponseError;
    if (err.errcode != null && err.errmsg != null) {
        let error = { name: err.errcode, message: err.errmsg };
        return Promise.reject(error);
    }

    return r;
}

type ResponseError = {
    errcode: string,
    errmsg: string,
}

